package com.yuncheng.spcyApi.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.spcyApi.constant.common.StatDwdEnumConstant;
import com.yuncheng.spcyApi.dto.sqsx.SqsxQueryStatDto;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.spcyApi.vo.common.PageVo;
import com.yuncheng.spcyApi.vo.sys.UserNameVo;
import com.yuncheng.spcyApi.vo.sys.UserRealnameVo;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.busService.SpcyTjService;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.mapper.SpcySqsxBaiscMapper;
import com.yuncheng.spcyApi.utils.ExcelServiceUtils;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.StartEndTimeVo;
import com.yuncheng.spcyApi.vo.sqsx.XcjcArrangeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import utils.DateConversionUtils;
import utils.ExcelUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "审评查验-查询统计接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyStat")
public class SpcyStatTjController {
    private static final Logger log = LoggerFactory.getLogger(SpcyStatTjController.class);

    @Resource
    private SpcyTjService spcyTjService;

    @Resource
    private SpcySqsxBaiscMapper spcySqsxBaiscMapper;

    @Resource
    private YcSysUserMapper ycSysUserMapper;

    @Log(title = "查询统计-每个科室-每个人的审评查验流程-统计数据")
//    @ApiOperation(value = "查询统计-每个科室-每个人的审评查验流程-统计数据")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "startTime",value = "开始时间，格式 yyyy-MM-dd HH:mm:ss, 时分秒为 00:00:00"),
            @ApiImplicitParam(name = "endTime",value = "结束时间，格式 yyyy-MM-dd HH:mm:ss, 时分秒为 00:00:00"),
            @ApiImplicitParam(name = "fywflcode",value = "业务分类：001002,001001,001003,002,003,可以给一个或者多个,给值可为（001002,001001）"),
            @ApiImplicitParam(name = "onlyCurrentUser",value = "是否查询个人（默认: false | true）"),
    })
    @GetMapping(value = "queryEachDeptAndPersonTjData")
    public HttpResult<?> queryEachDeptAndPersonTjData(StartEndTimeVo startEndTimeVo,
                                                      @RequestParam(value = "fywflcode",defaultValue = "")String fywflcodes){
        List<Map> resultList = new ArrayList<>();

        /*if (StringUtils.isBlank(fywflcodes)){
            Map ypscMapList = spcyTjService.queryEachDeptAndPersonTjData(SpcyConstant.YWFL_CODE_YPSC,startEndTimeVo,onlyCurrentUser);
            resultList.add(ypscMapList);

            Map ypzcMapList = spcyTjService.queryEachDeptAndPersonTjData(SpcyConstant.YWFL_CODE_YPZC,startEndTimeVo,onlyCurrentUser);
            resultList.add(ypzcMapList);

            Map ypltMapList = spcyTjService.queryEachDeptAndPersonTjData(SpcyConstant.YWFL_CODE_YPJY,startEndTimeVo,onlyCurrentUser);
            resultList.add(ypltMapList);

            Map ylqxMapList = spcyTjService.queryEachDeptAndPersonTjData(SpcyConstant.YWFL_CODE_YLQX,startEndTimeVo,onlyCurrentUser);
            resultList.add(ylqxMapList);

            Map hzpMapList = spcyTjService.queryEachDeptAndPersonTjData(SpcyConstant.YWFL_CODE_HZP,startEndTimeVo,onlyCurrentUser);
            resultList.add(hzpMapList);

        }else {
            List<String> ywflCodeList = Arrays.asList(fywflcodes.split(",|，"));

            for (String code : ywflCodeList) {
                Map mapList = spcyTjService.queryEachDeptAndPersonTjData(code, startEndTimeVo,onlyCurrentUser);
                resultList.add(mapList);
            }
        }*/
        if (StringUtils.isBlank(fywflcodes)) {
            fywflcodes = SpcyConstant.getYwflByDeptName(GetCurrentUserUtils.getCurrentUserOrgName());
        }
        Map mapList = spcyTjService.queryEachDeptAndPersonTjDataNew(fywflcodes, startEndTimeVo,false);
        resultList.add(mapList);

        return HttpResult.ok(resultList);
    }

    @Log(title = "查询统计-检查出勤量-年度-业务分类")
//    @ApiOperation(value = "查询统计-检查出勤量-年度-业务分类")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码"),
            @ApiImplicitParam(name = "fgzdw",value = "工作单位"),
            @ApiImplicitParam(name = "years",value = "选择的单个或者多个年度，逗号分割例如：（2022,2023）"),
            @ApiImplicitParam(name = "jclxs",value = "选择的单个或者多个检查类型，逗号分割例如：（xxx,xx,xxx）"),
            @ApiImplicitParam(name = "isSd",value = "是否勾选属地 (默认[true]/[flase])"),
            @ApiImplicitParam(name = "isYd",value = "是否勾选异地 (默认[true]/[flase])")
    })
    @GetMapping(value = "queryHcyCqlInTjData")
    public HttpResult<?> queryHcyCqlInTjData(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode,
                                             @RequestParam(value = "years",defaultValue = "")String years,
                                             @RequestParam(value = "jclxs",defaultValue = "")String jclxs,
                                             @RequestParam(value = "fgzdw",defaultValue = "")String fgzdw,
                                             @RequestParam(value = "isSd",defaultValue = "true")boolean isSd,
                                             @RequestParam(value = "isYd",defaultValue = "true")boolean isYd){
        if (StringUtils.isBlank(fywflcode)){
            fywflcode = SpcyConstant.getYwflByDeptName(GetCurrentUserUtils.getCurrentUserOrgName());
        }

        List<List<String>> hcyCqlTjList = spcyTjService.queryHcyCqlInTjData(fywflcode, years, jclxs, fgzdw, isSd, isYd);
        List<List<String>> jclxYearTjList = spcyTjService.queryJclxYearTjData(fywflcode, years, jclxs);
        Map resultMap = new HashMap();

        resultMap.put("cqlTjList",hcyCqlTjList);
        resultMap.put("yearTjList",jclxYearTjList);
        return HttpResult.ok(resultMap);
    }

    @Log(title = "查询统计-年度-检查类型")
//    @ApiOperation(value = "查询统计-年度-检查类型")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码"),
            @ApiImplicitParam(name = "years",value = "选择的单个或者多个年度，逗号分割例如：（2022,2023）"),
            @ApiImplicitParam(name = "jclxs",value = "选择的单个或者多个检查类型，逗号分割例如：（xxx,xx,xxx）"),
            @ApiImplicitParam(name = "isSd",value = "是否勾选属地 (默认[true]/[flase])"),
            @ApiImplicitParam(name = "isYd",value = "是否勾选异地 (默认[true]/[flase])")
    })
    @GetMapping(value = "queryJclxYearTjData")
    public HttpResult<?> queryJclxYearTjData(@RequestParam("fywflcode")String fywflcode,
                                             @RequestParam(value = "years",defaultValue = "")String years,
                                             @RequestParam(value = "jclxs",defaultValue = "")String jclxs){
        if (StringUtils.isBlank(fywflcode)){
            return HttpResult.error("业务分类编码不能为空");
        }
        List<List<String>> lists = spcyTjService.queryJclxYearTjData(fywflcode, years, jclxs);
        return HttpResult.ok(lists);
    }

    @Log(title = "查询统计-审评查验中心各科室现场检查计划安排汇总情况表")
//    @ApiOperation(value = "查询统计-审评查验中心各科室现场检查计划安排汇总情况表")
    @GetMapping(value = "selectXcjcArrangePageList")
    public HttpResult<?> selectXcjcArrangePageList(XcjcArrangeVo arrangeVo,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){

        Page<XcjcArrangeVo> page = new Page<>(pageNo,pageSize);
        IPage<XcjcArrangeVo> pageList = spcySqsxBaiscMapper.selectXcjcArrangePageList(page, arrangeVo);

        if (StringUtils.isNotBlank(arrangeVo.getJcry())){
            if (CollectionUtils.isNotEmpty(pageList.getRecords())){
                List<XcjcArrangeVo> collect = pageList.getRecords()
                        .stream()
                        .filter(f -> StringUtils.isNotBlank(f.getJcry())
                                && f.getJcry().contains(arrangeVo.getJcry()))
                        .collect(Collectors.toList());
                pageList.setRecords(collect);
                pageList.setTotal(collect.size());
            }
        }
        return HttpResult.ok(pageList);
    }

    @Log(title = "导出统计-审评查验中心各科室现场检查计划安排汇总情况表")
//    @ApiOperation(value = "导出统计-审评查验中心各科室现场检查计划安排汇总情况表")
    @GetMapping(value = "exportXcjcArrange")
    public void exportXcjcArrange(XcjcArrangeVo arrangeVo,HttpServletResponse response){
        List<XcjcArrangeVo> list = spcySqsxBaiscMapper.selectXcjcArrangeList(arrangeVo);

        if (StringUtils.isNotBlank(arrangeVo.getJcry())){
            if (CollectionUtils.isNotEmpty(list)){
                List<XcjcArrangeVo> collect = list
                        .stream()
                        .filter(f -> StringUtils.isNotBlank(f.getJcry())
                                && f.getJcry().contains(arrangeVo.getJcry()))
                        .collect(Collectors.toList());
                list = collect;
            }
        }

        List<XcjcArrangeVo> hzpList = new ArrayList<>();
        List<XcjcArrangeVo> ypzcList = new ArrayList<>();
        List<XcjcArrangeVo> ypscList = new ArrayList<>();
        List<XcjcArrangeVo> ypltList = new ArrayList<>();
        List<XcjcArrangeVo> ylqxList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)){
            hzpList = list.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFywflcode())
                            && f.getFywflcode().equals(SpcyConstant.YWFL_CODE_HZP)).collect(Collectors.toList());

            ypzcList = list.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFywflcode())
                            && f.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPZC)).collect(Collectors.toList());

            ypscList = list.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFywflcode())
                            && f.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPSC)).collect(Collectors.toList());

            ypltList = list.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFywflcode())
                            && f.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPJY)).collect(Collectors.toList());

            ylqxList = list.stream()
                    .filter(f->StringUtils.isNotBlank(f.getFywflcode())
                            && f.getFywflcode().equals(SpcyConstant.YWFL_CODE_YLQX)).collect(Collectors.toList());
        }
        ExcelServiceUtils.createXcjcArrangeExcel(hzpList, ypzcList, ypscList, ypltList, ylqxList, response);
    }

    @Log(title = "导出统计-检查员年度检查出勤量-年度-业务分类")
//    @ApiOperation(value = "导出统计-检查员年度检查出勤量-年度-业务分类")
    @ApiImplicitParams(value = {

    })
    @GetMapping(value = "exportHcyCqlInTjData")
    public void exportHcyCqlInTjData(@RequestParam("fywflcode")String fywflcode,
                                     @RequestParam(value = "years",defaultValue = "")String years,
                                     @RequestParam(value = "jclxs",defaultValue = "")String jclxs,
                                     @RequestParam(value = "fgzdw",defaultValue = "")String fgzdw,
                                     @RequestParam(value = "isSd",defaultValue = "true")boolean isSd,
                                     @RequestParam(value = "isYd",defaultValue = "true")boolean isYd,
                                     HttpServletResponse response){
        if (StringUtils.isBlank(fywflcode)){
            throw new BusinessException("业务分类编码不能为空");
        }
        List<List<String>> hcyCqlTjList = spcyTjService.queryHcyCqlInTjData(fywflcode, years, jclxs, fgzdw, isSd, isYd);
        ExcelUtils.getLocalExcel(hcyCqlTjList,"检查员年度检查出勤率",response);
    }

    @Log(title = "导出统计-检查类型量-年度-业务分类")
//    @ApiOperation(value = "导出统计-检查类型量-年度-业务分类")
    @ApiImplicitParams(value = {

    })
    @GetMapping(value = "exportJclxYearTjData")
    public void exportJclxYearTjData(@RequestParam("fywflcode")String fywflcode,
                                     @RequestParam(value = "years",defaultValue = "")String years,
                                     @RequestParam(value = "jclxs",defaultValue = "")String jclxs,
                                     @RequestParam(value = "isSd",defaultValue = "true")boolean isSd,
                                     @RequestParam(value = "isYd",defaultValue = "true")boolean isYd,
                                     HttpServletResponse response){
        if (StringUtils.isBlank(fywflcode)){
            throw new BusinessException("业务分类编码不能为空");
        }
        List<List<String>> hcyCqlTjList = spcyTjService.queryJclxYearTjData(fywflcode, years, jclxs);
        ExcelUtils.getLocalExcel(hcyCqlTjList,"检查年度类型出勤率",response);
    }

    /***************************【 特药审评统计相关 】*********************************************************/

    @Log(title = "特药审评-环节统计")
    @ApiOperation(value = "特药审评-环节统计")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "startTime",value = "开始时间，格式 yyyy-MM-dd HH:mm:ss, 时分秒为 00:00:00"),
            @ApiImplicitParam(name = "endTime",value = "结束时间，格式 yyyy-MM-dd HH:mm:ss, 时分秒为 00:00:00"),
            @ApiImplicitParam(name = "fywflcode",value = "业务分类：001002,001001,001003,002,003,可以给一个或者多个,给值可为（001002,001001）")
    })
    @GetMapping(value = "queryEachDeptTjData")
    public HttpResult<?> queryEachDeptTjData(StartEndTimeVo startEndTimeVo,
                                             @RequestParam(value = "fywflcode",defaultValue = "")String fywflcodes){
        List<Map> resultList = new ArrayList<>();

        /*if (StringUtils.isBlank(fywflcodes)) {
            fywflcodes = SpcyConstant.getYwflByDeptName(GetCurrentUserUtils.getCurrentUserOrgName());
        }*/
        fywflcodes = SpcyConstant.YWFL_CODE_YPSC;

        resultList.add(spcyTjService.queryEachDeptTjDataNew(fywflcodes, "专家", startEndTimeVo));

        return HttpResult.ok(resultList);
    }

    @ApiOperation(value = "特药审评-查询统计-查询")
    @GetMapping(value = "tyCxtjSelect")
    public HttpResult tyCxtjSelect(PageVo pageVo, SqsxQueryStatDto query){
        Page<SqsxQueryStatDto> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());

        Page<SqsxQueryStatDto> pageList = spcySqsxBaiscMapper.selectQueryStatSqsxPage(page, query);
        return HttpResult.ok(pageList);
    }

    @ApiOperation(value = "特药审评-查询统计-导出")
    @GetMapping(value = "tyCxtjExport")
    public void tyCxtjExport(SqsxQueryStatDto query, HttpServletResponse response){

        List<SqsxQueryStatDto> statDataList = spcySqsxBaiscMapper.selectQueryStatSqsxList(query);
        List<List<String>> exportDataList = spcyTjService.genTyCxtjExport(statDataList);
        ExcelUtils.getLocalExcel(exportDataList,"查询统计", response);
    }

    @ApiOperation(value = "特药审评-多维度统计-获取审评专家列表")
    @GetMapping(value = "tySpzjlb")
    public HttpResult tySpzjlb(){

        return HttpResult.ok(ycSysUserMapper.selectUserExistsXpjlList());
    }

    @ApiOperation(value = "特药审评-多维度统计-根据不同维度查询统计结果")
    @GetMapping(value = "tydwdTj")
    public HttpResult tydwdTj(
            @RequestParam(value = "ids",defaultValue = "") @ApiParam(value = "专家人员id,多个人员逗号英文逗号拼接") String ids,
            @RequestParam(value = "tjwd",defaultValue = "") @ApiParam(value = "统计维度,多个数据集逗号分割【fsqfl：申请分类; fzcfl：注册分类; fqwfl: 勤务分类;】") String tjwd,
            @RequestParam(value = "tjkj",defaultValue = "") @ApiParam(value = "统计口经,多个数据集逗号分割【hjs: 合计数; tgs: 通过数; btgs: 不通过数;】") String tjkj
    ){

        if (StringUtils.isBlank(tjwd)){
            return HttpResult.error("请至少选择一个统计维度！");
        }

        List<String> titleIndxList = new ArrayList<>();  // 表头内容字段
        List<String> titleList = new ArrayList<>();  // 表头内容字段对应中午名
        titleList.add("序 号");

        // 查询需要查询的专家，存在专家第二列为 专家姓名列
        List<UserRealnameVo> userList = null;
        if (StringUtils.isNotBlank(ids)){
            userList = ycSysUserMapper.findRealnameListsByIdsOrder(StringPatternUtils.getListByIds(ids));
            titleList.add("专 家");
        }

        List<String> tjwdList = StringPatternUtils.getListByIds(tjwd);
        List<String> tjkjList = StringPatternUtils.getListByIds(tjkj);

        String selectSql = "";  // 查询sql
        String groupBy = ""; // 分组sql

        /** 构建sql、构建分组sql、构建表头字段及内容 */
        for (String wd : tjwdList){

            if (!StatDwdEnumConstant.isExistsIndex(wd)){
                return HttpResult.error("统计维度：[" + wd + "]字段不合法！");
            }

            // 构建sql
            if (StringUtils.isNotBlank(selectSql)){
                selectSql += ",";
            }
            selectSql += wd;

            // 构建分组sql
            if (StringUtils.isNotBlank(groupBy)){
                groupBy += ",";
            }
            groupBy += wd;

            // 构建表头字段及内容
            if (StatDwdEnumConstant.TJWD_fsqfl.getIndex().equalsIgnoreCase(wd)){
                titleList.add(StatDwdEnumConstant.TJWD_fsqfl.getName());
                titleIndxList.add(wd);
            }
            else if (StatDwdEnumConstant.TJWD_fzcfl.getIndex().equalsIgnoreCase(wd)){
                titleList.add(StatDwdEnumConstant.TJWD_fzcfl.getName());
                titleIndxList.add(wd);
            }
            else if (StatDwdEnumConstant.TJWD_fqwfl.getIndex().equalsIgnoreCase(wd)){
                titleList.add(StatDwdEnumConstant.TJWD_fqwfl.getName());
                titleIndxList.add(wd);
            }

        }

        /** 构建sql、构建分组sql、构建表头字段及内容 */
        for (String kj : tjkjList){

            if (!StatDwdEnumConstant.isExistsIndex(kj)){
                return HttpResult.error("统计口径：[" + kj + "]字段不合法！");
            }

            // 构建表头字段及内容
            if (StatDwdEnumConstant.TJKJ_hjs.getIndex().equalsIgnoreCase(kj)){

                // 构建sql
                if (StringUtils.isNotBlank(selectSql)){
                    selectSql += ",";
                }
                selectSql += "count(*) as " + kj;

                titleList.add(StatDwdEnumConstant.TJKJ_hjs.getName());
                titleIndxList.add(kj);
            }
            else if (StatDwdEnumConstant.TJKJ_tgs.getIndex().equalsIgnoreCase(kj)){

                // 构建sql
                if (StringUtils.isNotBlank(selectSql)){
                    selectSql += ",";
                }
                selectSql += "count(case when fzhjg = '符合' then 1 end) as " + kj;

                titleList.add(StatDwdEnumConstant.TJKJ_tgs.getName());
                titleIndxList.add(kj);
            }
            else if (StatDwdEnumConstant.TJKJ_btgs.getIndex().equalsIgnoreCase(kj)){

                // 构建sql
                if (StringUtils.isNotBlank(selectSql)){
                    selectSql += ",";
                }
                selectSql += "count(case when fzhjg = '不符合' then 1 end) as " + kj;

                titleList.add(StatDwdEnumConstant.TJKJ_btgs.getName());
                titleIndxList.add(kj);
            }
        }

        // 二维数据结果集，首行为表头
        List<List<String>> resultDataList = new ArrayList<>();
        resultDataList.add(titleList);

        // 构建数据集
        if (CollectionUtil.isNotEmpty(userList)){
            int order = 1;
            for (UserRealnameVo user : userList){
                // 根据sql进行分组查询数据集
                List<Map> mapStatList = spcySqsxBaiscMapper.selectDwdStatGroup(selectSql, groupBy, user.getId());
                resultDataList.addAll(spcyTjService.genTydwdTj(order, mapStatList, titleIndxList, user.getRealname()));
                order += mapStatList.size();
//                order++;
            }
        }else {
            // 根据sql进行分组查询数据集
            List<Map> mapStatList = spcySqsxBaiscMapper.selectDwdStatGroup(selectSql, groupBy, null);
            resultDataList.addAll(spcyTjService.genTydwdTj(1, mapStatList, titleIndxList, null));
        }

        return HttpResult.ok(resultDataList);
    }


    @ApiOperation(value = "特药审评-评价统计-年度评价统计")
    @GetMapping(value = "tyPjStatYear")
    public HttpResult tyPjStatYear(@RequestParam(value = "year",defaultValue = "") @ApiParam(value = "年度") String year){
        if (StringUtils.isBlank(year)){
            year = DateConversionUtils.DateToYear(new Date());
        }

        return HttpResult.ok(spcyTjService.genTyPjStatYear(year));
    }

    @ApiOperation(value = "特药审评-评价统计-审评专家评价-查询")
    @GetMapping(value = "tyPjTjZj")
    public HttpResult tyPjTjZj(@RequestParam(value = "year",defaultValue = "") @ApiParam(value = "年度") String year){
        if (StringUtils.isBlank(year)){
            year = DateConversionUtils.DateToYear(new Date());
        }

        List<UserNameVo> userList = ycSysUserMapper.selectUserExistsXpjlList();

        return HttpResult.ok(spcyTjService.genTyPjTjZj(year, userList));
    }

    @ApiOperation(value = "特药审评-评价统计-审评专家评价-导出")
    @GetMapping(value = "tyPjTjZjExport")
    public void tyPjTjZjExport(@RequestParam(value = "year",defaultValue = "") @ApiParam(value = "年度") String year,
                               HttpServletResponse response){

        if (StringUtils.isBlank(year)){
            year = DateConversionUtils.DateToYear(new Date());
        }

        List<UserNameVo> userList = ycSysUserMapper.selectUserExistsXpjlList();
        ExcelUtils.getLocalExcel(spcyTjService.genTyPjTjZj(year, userList),"审评专家评价", response);
    }


}
